package com.wichell.framework.dfs.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;

import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.log4j.Logger;
import org.lokra.seaweedfs.core.FileSource;
import org.lokra.seaweedfs.core.FileTemplate;
import org.lokra.seaweedfs.core.file.FileHandleStatus;
import org.lokra.seaweedfs.core.http.StreamResponse;

import com.wichell.framework.dfs.dto.ResourceDto;
import com.wichell.framework.dfs.exception.ResourceNotFoundException;
import com.wichell.framework.dfs.exception.ResourceRequestException;
import com.wichell.framework.dfs.util.ResourceUtil;
import com.wichell.framework.util.Base64Util;

public class WeedfsResouceServiceImpl implements ResourceService {

	private static Logger LOGGER = Logger.getLogger(WeedfsResouceServiceImpl.class);

	private FileSource fileSource;

	public WeedfsResouceServiceImpl(FileSource fileSource) {
		super();
		this.fileSource = fileSource;
	}

	@Override
	public String upload(String resourceName, InputStream resourceContent) throws ResourceRequestException {
		FileTemplate template = new FileTemplate(fileSource.getConnection());
		try {
			ContentType contentType = ContentType.create(ResourceUtil.convertContentTypeByFileName(resourceName),
					Consts.UTF_8);
			FileHandleStatus status = template.saveFileByStream(resourceName, resourceContent, contentType);
			return status.getFileId();
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.error(MessageFormat.format("上传文件[{0}]失败，原因：[{1}]", resourceName, e.getMessage()));
			throw new ResourceRequestException(
					MessageFormat.format("上传文件[{0}]失败，原因：[{1}]", resourceName, e.getMessage()));
		}
	}

	@Override
	public ResourceDto download(String resourceCode) throws ResourceRequestException, ResourceNotFoundException {
		FileTemplate template = new FileTemplate(fileSource.getConnection());
		try {
			StreamResponse response = template.getFileStream(resourceCode);
			if (HttpStatus.SC_OK == response.getHttpResponseStatusCode()) {
				FileHandleStatus status = template.getFileStatus(resourceCode);
				byte[] content = ResourceUtil.streamToByte(response.getInputStream());
				ResourceDto dto = new ResourceDto(resourceCode, status.getFileName(), content,
						Base64Util.base64Encode(content));
				return dto;
			} else if (HttpStatus.SC_NOT_FOUND == response.getHttpResponseStatusCode()) {
				LOGGER.error(MessageFormat.format("资源[{0}]未找到，请确认Code是否正确", resourceCode));
				throw new ResourceNotFoundException(MessageFormat.format("资源[{0}]未找到，请确认Code是否正确", resourceCode));
			} else {
				LOGGER.error("资源请求失败，HTTP请求码为" + response.getHttpResponseStatusCode());
				throw new ResourceRequestException("资源请求失败，HTTP请求码为" + response.getHttpResponseStatusCode());
			}
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.error(MessageFormat.format("获取资源[{0}]异常，原因：[{1}]", resourceCode, e.getMessage()));
			throw new ResourceRequestException(
					MessageFormat.format("获取资源[{0}]异常，原因：[{1}]", resourceCode, e.getMessage()));
		}

	}

	@Override
	public void destroy() {
		try {
			this.fileSource.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setFileSource(FileSource fileSource) {
		this.fileSource = fileSource;
	}
}
